package com.yao2san.simcasserver.filter;

import com.yao2san.simcasserver.processor.AbstractDatabaseAuthenticationProcessor;
import com.yao2san.simcasserver.processor.DefaultAuthenticationObject;

import javax.servlet.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * authentication for form object
 */
public class AuthenticationFilter implements Filter {

    private AbstractDatabaseAuthenticationProcessor abstractDatabaseAuthenticationProcessor;

    public AuthenticationFilter(AbstractDatabaseAuthenticationProcessor abstractDatabaseAuthenticationProcessor) {
        this.abstractDatabaseAuthenticationProcessor = abstractDatabaseAuthenticationProcessor;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Map<String, String> params = this.getRequestParams(servletRequest);
        DefaultAuthenticationObject defaultAuthenticationObject = new DefaultAuthenticationObject();
        defaultAuthenticationObject.setServletRequest(servletRequest);
        defaultAuthenticationObject.setServletResponse(servletResponse);
        defaultAuthenticationObject.setAuthenticationParameter(params);
        this.abstractDatabaseAuthenticationProcessor.process(defaultAuthenticationObject);
    }

    private Map<String, String> getRequestParams(ServletRequest servletRequest) {
        Map<String, String[]> parameterMap = servletRequest.getParameterMap();
        Map<String, String> paramsMap = new HashMap<>();
        if (parameterMap != null) {
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                if (entry.getValue() != null && entry.getValue().length > 0) {
                    paramsMap.put(entry.getKey(), entry.getValue()[0]);
                }
            }
        }
        return paramsMap;
    }
}
